import { queryAllDictListApi, queryCurrentAccountPeriodApi, queryMerchantDetailsListApi, queryVenueList } from "@/api/common"
import { queryGameRecordTypeSection } from "@/api/game-betslip"
import http, { httpB } from "@/api/helper/request"
import { DICT_DEFAULT_CONFIG } from "@/constants/dict"
import { BetType, RateType } from "@/interface/store/config"
import { localStg, sessionStg } from "@/utils/storage"

export const verifyCurrentAccountPeriod = (currentAccountPeriod: FormConfig.CurrentAccountPeriod) =>
	currentAccountPeriod.start &&
	currentAccountPeriod.end &&
	currentAccountPeriod.end > new Date().getTime() &&
	currentAccountPeriod.expired > new Date().getTime()

export const handleUpdateCurrentAccountPeriod = async (): Promise<FormConfig.CurrentAccountPeriod> => {
	const result: FormConfig.CurrentAccountPeriod = {
		start: 0,
		end: 0,
		expired: 0
	}
	const [, data] = await queryCurrentAccountPeriodApi()

	if (data) {
		result.start = parseInt(data?.periodStTimeMillis) || 0
		result.end = parseInt(data?.periodEnTimeMillis) || 0
		result.end && result.end > new Date().getTime() && result.end + 999
		result.expired = 60 * 60 * 1000 + new Date().getTime()
	}
	sessionStg.set("__currentAccountPeriod__", result)
	return result
}

/** 获取token */
export function getCurrentAccountPeriod(): FormConfig.CurrentAccountPeriod {
	const result: FormConfig.CurrentAccountPeriod =
		sessionStg.get("__currentAccountPeriod__") || ({} as FormConfig.CurrentAccountPeriod)
	!verifyCurrentAccountPeriod(result) && handleUpdateCurrentAccountPeriod()

	return result
}

const allDictResponse = async (): Promise<FormConfig.DictLists> => {
	const [, data] = await queryAllDictListApi()
	if (!data) {
		return {} as FormConfig.DictLists
	}
	return Object.keys(data).reduce(
		(res: FormConfig.DictLists, key) => ({
			...res,
			[key]: data[key].map((item: { code: any; description: any }) => ({
				value: item.code,
				label: item.description
			}))
		}),
		{}
	)
}

export const handleUpdateAllDictList = async (): Promise<{ allDictLists: FormConfig.DictLists; ready: boolean }> => {
	const [, data] = await queryGameRecordTypeSection()
	const allDicts = await allDictResponse()
	const [err, data1] = await queryVenueList()
	const venueTypes = {
		venueList: !err
			? (data1 as any).map((item: { venueName: any; venueCode: any }) => {
					return { label: item.venueName, value: item.venueCode }
			  })
			: []
	}
	const betTypes =
		data?.reduce(
			(prev, item) => {
				prev.parentBetTypes.push({
					value: item.type,
					label: item.desc
				})
				const currentSub = item.subList.map(subItem => ({
					value: subItem.type,
					label: subItem.desc
				}))
				prev.subBetTypes_all.push(...currentSub)
				prev[`subBetTypes_${item.type}`] = currentSub
				return prev
			},
			{
				parentBetTypes: [],
				subBetTypes_all: []
			} as Record<string, FormConfig.ValueNLabel[]>
		) ?? []
	const allDictLists = {
		...allDicts,
		...DICT_DEFAULT_CONFIG,
		...betTypes,
		...venueTypes
	}
	localStg.set(`__allDictList__`, allDictLists)
	return { allDictLists, ready: Object.keys(allDicts).length > 0 }
}

/** 获取AllDictLists */
export function getAllDictLists(): FormConfig.DictLists {
	const result: FormConfig.DictLists = localStg.get("__allDictList__") || ({} as FormConfig.DictLists)
	if (!result) handleUpdateAllDictList()

	return result
}

export const handleUpdateMerchantList = async (): Promise<FormConfig.MerchantDetailsList> => {
	const [, data] = await queryMerchantDetailsListApi()

	if (!data) return [] as FormConfig.MerchantDetailsList
	localStg.set(`__merchantList__`, data)

	return data
}
export const getBetTypes = async (): Promise<BetType[]> => {
	const [err, data] = await httpB.post("/dx-game-data-manager/dxGameRecords/getGameRecoedTypeSection", {})
	if (!err) return data as BetType[]
	else return []
}

export function getMerchantList(): FormConfig.MerchantDetailsList {
	const result: FormConfig.MerchantDetailsList = localStg.get("__merchantList__") || ([] as FormConfig.MerchantDetailsList)
	!result && handleUpdateMerchantList()

	return result
}

export const deepTraversalMerchantList = (data: FormConfig.MerchantDetailsList): FormConfig.ValueNLabel[] =>
	data.reduce((res: FormConfig.ValueNLabel[], item) => {
		res.push({
			value: item.id,
			// label: `merchantList.${item.id}`,
			label: item.merchantName,
			...item
		} as FormConfig.ValueNLabel)
		item.children && item.children.length > 0 && res.push(...deepTraversalMerchantList(item.children))
		return res
	}, [])

export const getRateLimit = async (body: { platformFlag: number; userType: number; zhanchengFlag: number }) => {
	const [err, data] = await http.post("/rebateRate/queryLimit", body)
	if (!err) return data as Partial<RateType>
	else return null
}
